<script setup lang="ts">
import AddWrite from './components/addWrite.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref, unref } from 'vue'
import { ElButton } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { storageAdd } from '@/api/common'
import { storageType } from '@/api/common/types'

const { emitter } = useEmitt()

const { push } = useRouter()

const { t } = useI18n()

const addWrite = ref<ComponentRef<typeof AddWrite>>()

const loading = ref(false)

const save = async () => {
  const write = unref(addWrite)
  // console.log('---addWrite---', write?.getRlus().value?.validate())
  write?.getRlus().value?.validate(async (valid, fields) => {
    if (valid) {
      let goodsArr: any = []
      write?.getFormData()?.pieceArray.forEach(async (item) => {
        if (item.gname) {
          let obj = {
            gname: item.gname,
            worth: item.worth,
            goods_id: item.goods_id,
            piece: item.piece || 1,
            quantity: item.quantity,
            room: item.room,
            colour: item.colour,
            length: item.length,
            width: item.width,
            high: item.high,
            weight: item.weight,
            remark: item.remark,
            total: item.total
          }
          goodsArr.push(obj)
        }
      })
      const data: any = {
        goods_id: write?.getFormData()?.typeOfGoods,
        store_id: write?.getFormData()?.store_id,
        transport: write?.getFormData()?.modeOfTransport,
        placestart: write?.getFormData()?.origin,
        client_code: write?.getFormData()?.relatedCustomers,
        remark: write?.getFormData()?.productNameRemarks,
        piece: write?.getFormData()?.warehousingItems,
        entertime: Number(new Date(write?.getFormData()?.warehousingTime).valueOf()) / 1000,
        // entertime: write?.getFormData()?.warehousingTime,
        shouhuo: write?.getFormData()?.recipient,
        placeend: write?.getFormData()?.destination,
        out_date: write?.getFormData()?.out_date,
        submarket: write?.getFormData()?.submarket,
        fahuo: write?.getFormData()?.fahuo,
        goods: goodsArr
      }
      // data.buytime = '' + parseInt(data.buytime) / 1000
      console.log('---入库单新增参数---', goodsArr)
      const res = await storageAdd(data)
      if (res) {
        emitter.emit('getList', 'add')
        push('/logistics/warehousingEntry')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<template>
  <ContentDetailWrap :title="t('exampleDemo.add')" @back="push('/logistics/warehousingEntry')">
    <!-- <Write ref="writeRef" /> -->
    <AddWrite ref="addWrite" />

    <template #right>
      <ElButton type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
    </template>
  </ContentDetailWrap>
</template>
